package com.jichangxiu.framework.encoder;

import cn.hutool.core.util.ObjectUtil;
import com.jichangxiu.common.constant.Constants;
import com.jichangxiu.common.utils.EncodeUtils;
import com.jichangxiu.common.utils.RsaUtils;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@NoArgsConstructor
public class PasswordEncoder extends BCryptPasswordEncoder {

    @Override
    public boolean matches(CharSequence uiPassword, String encodedPassword) {
        // 接收到的前端的密码
        String password = uiPassword.toString();
        if (Constants.JCX_PROPERTIES.getSecurityProperties().getLoginPasswordRsaEnabled()) {
            // 进行rsa解密
            try {
                password = RsaUtils.decrypt(password, RsaUtils.getPrivateKey());
            } catch (Exception ex) {
                return false;
            }
        }
        if (ObjectUtil.isNotNull(encodedPassword))
            return EncodeUtils.bcCompare(password, encodedPassword);
        else
            return false;
    }

}
